<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>ajax post练习</h1>
    <form id="form">
        <input id="ipt" type="text" name="name">
        <input id="ipt2" type="text" name="age">
        <button id="btn">发送请求</button>
    </form>
    <script>
        const oBtn = document.querySelector('#btn')
        const oIpt = document.querySelector('#ipt')
        const oIpt2 = document.querySelector('#ipt2')
        const oForm = document.querySelector('#form')
        
        oForm.onsubmit = function(){
            const userName = oIpt.value
            const userAge = oIpt2.value


            const xhr = new XMLHttpRequest();

            xhr.open('POST','/post',true)
            //设置请求头
            xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")
            // 发送请求体
            xhr.send(JSON.stringify({
                name:userName,
                age:userAge
            }));

            xhr.onreadystatechange  = function(){
                if(xhr.readyState ===4 && xhr.status>=200&&xhr.status<=299){
                    
                    console.log( xhr.responseText);
                }
            }
            // 终止表单自动提交
            return false
        }
    </script>

</body>
</html>